#pragma once

#include <iostream>
#include <string>
#include <vector>
#include "InetAddr.hpp"
class Route
{
private:
    bool IsExists(const InetAddr &addr)
    {
        for (auto &e : _online_user)
        {
            if (e == addr)
                return true;
        }
        return false;
    }
    void AddUser(const InetAddr &addr)
    {
        if (!IsExists(addr))
            _online_user.push_back(addr);
    }
    void SendMessageToAll(int sockfd, std::string &message, InetAddr &addr)
    {
        for (auto &e : _online_user)
        {
            LOG(LogLevel::DEBUG) << "route [" << message << "] to: " << e.ToString();
            std::string info = addr.ToString();
            info += "# ";
            info += message;
            sendto(sockfd, message.c_str(), message.size(), 0, e.Addr(), e.Length());
        }
    }
    void DeleteUser(const std::string &message, const InetAddr &addr)
    {
        if (message == "QUIT")
        {
            auto iter = _online_user.begin();
            for (; iter < _online_user.end(); iter++)
            {
                if (*iter == addr)
                {
                    _online_user.erase(iter);
                }
                break;
            }
        }
    }

public:
    Route()
    {
    }

    void RouteMessageToAll(int sockfd, std::string &message, InetAddr &addr)
    {
        AddUser(addr);
        SendMessageToAll(sockfd, message,addr);
        DeleteUser(message, addr);
    }
    ~Route()
    {
    }

private:
    // 临界资源
    // 1. 锁
    std::vector<InetAddr> _online_user;

    // 2. 锁 + 拷贝
    // std::vector<InetAddr> _send_lint;

};
